﻿using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SmartPlant.Model
{
    /// <summary>
    /// 动态生成实体的基类。
    /// </summary>
    public abstract class DynamicEntity : INotifyPropertyChanged
    {
        public bool IsModify { get; set; } = false;

        /// <summary>
        /// 属性更改事件。
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 设置指定属性值，并触发属性更改事件。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="storage"></param>
        /// <param name="value"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(storage, value))
            {
                return false;
            }
            if (propertyName != nameof(IsModify))
                IsModify = true;
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
                propertyChanged(this, e);
            }
        }
    }
}
